<template>
  <el-container>
    <el-main>
      <el-form :model="form.model" :rules="form.rules" ref="formRef" label-width="100px">
        <el-form-item label="模板名称" prop="name">
          <el-input v-model="form.model.name" placeholder="请输入模板名称"></el-input>
        </el-form-item>
        <template v-if="form.model.type == 'express'">
          <el-form-item label="计价方式">
            <el-radio-group v-model="priceType">
              <el-radio label="number">按件数</el-radio>
              <el-radio label="weight">按重量</el-radio>
            </el-radio-group>
          </el-form-item>
          <div class="template-wrap">
            <div class="title sa-flex">
              <div class="area">可配送区域</div>
              <div class="num" v-if="priceType == 'number'">首件</div>
              <div class="num" v-if="priceType == 'weight'">首重(kg)</div>
              <div class="num">运费(元)</div>
              <div class="num" v-if="priceType == 'number'">续件</div>
              <div class="num" v-if="priceType == 'weight'">续重(kg)</div>
              <div class="num">续费(元)</div>
              <div class="num">操作</div>
            </div>
            <sa-draggable v-model="form.model.express" :animation="300" handle=".sortable-drag" item-key="element">
              <template #item="{ element, index }">
                <div class="item">
                  <el-form-item class="area" :prop="'express.' + index + '.district_text'"
                    :rules="templateRules.district_text">
                    <el-button @click="selectArea(index)" v-if="!element.district_text" type="primary">选择地址</el-button>
                    <div class="sa-flex sa-row-between area-edit" v-if="element.district_text">
                      <div>{{ element.district_text }}</div>
                      <el-button class="is-link sa-m-l-4" type="primary" @click="selectArea(index)">选择</el-button>
                    </div>
                  </el-form-item>
                  <el-form-item class="num" :prop="'express.' + index + '.first_num'" :rules="templateRules.first_num"
                    v-if="priceType == 'number'">
                    <el-input placeholder="请输入首件" type="number" min="0" v-model="element.first_num">
                    </el-input>
                  </el-form-item>
                  <el-form-item class="num" :prop="'express.' + index + '.first_num'" :rules="templateRules.first_num"
                    v-if="priceType == 'weight'">
                    <el-input placeholder="请输入首重" type="number" min="0" v-model="element.first_num">
                    </el-input>
                  </el-form-item>
                  <el-form-item class="num" :prop="'express.' + index + '.first_price'"
                    :rules="templateRules.first_price">
                    <el-input placeholder="请输入运费" type="number" min="0" :step="0.01" v-model="element.first_price">
                    </el-input>
                  </el-form-item>
                  <el-form-item class="num" :prop="'express.' + index + '.additional_num'"
                    :rules="templateRules.additional_num" v-if="priceType == 'number'">
                    <el-input placeholder="请输入续件" type="number" min="0" v-model="element.additional_num">
                    </el-input>
                  </el-form-item>
                  <el-form-item class="num" :prop="'express.' + index + '.additional_num'"
                    :rules="templateRules.additional_num" v-if="priceType == 'weight'">
                    <el-input placeholder="请输入续重" type="number" min="0" v-model="element.additional_num">
                    </el-input>
                  </el-form-item>
                  <el-form-item class="num" :prop="'express.' + index + '.additional_price'"
                    :rules="templateRules.additional_price">
                    <el-input placeholder="请输入续费" type="number" min="0" :step="0.01" v-model="element.additional_price">
                    </el-input>
                  </el-form-item>
                  <el-form-item class="num">
                    <el-popconfirm width="fit-content" confirm-button-text="确认" cancel-button-text="取消" title="确认删除这条记录?"
                      @confirm="deleteTemplate(index)">
                      <template #reference>
                        <el-button class="is-link" type="danger" plain @click.stop>删除</el-button>
                      </template>
                    </el-popconfirm>
                    <sa-svg class="sa-m-l-8 sortable-drag" name="sa-round"></sa-svg>
                  </el-form-item>
                </div>
              </template>
            </sa-draggable>
            <el-button @click="addTemplate()" class="sa-m-l-16" type="primary" plain icon="Plus">添加</el-button>
          </div>
        </template>
        <template v-if="form.model.type == 'autosend'">
          <el-form-item label="发货类型：">
            <el-radio-group v-model="form.model.autosend.type" @change="onChangeAutosendType">
              <el-radio label="text">固定内容</el-radio>
              <el-radio label="params">自定义内容</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item v-if="form.model.autosend.type == 'text'" label="发货内容：">
            <el-input v-model="form.model.autosend.content" placeholder="请输入自动发货内容"></el-input>
          </el-form-item>
          <el-form-item v-if="form.model.autosend.type == 'params'" label="发货内容：">
            <div class="sa-template-wrap">
              <div class="title sa-flex">
                <div class="key">参数名称</div>
                <div class="key">内容</div>
                <div class="oper">操作</div>
              </div>
              <sa-draggable v-model="form.model.autosend.content" :animation="300" handle=".sortable-drag"
                item-key="element">
                <template #item="{ element, index }">
                  <div class="item">
                    <el-form-item class="key">
                      <el-input placeholder="请输入" v-model="element.title">
                      </el-input>
                    </el-form-item>
                    <el-form-item class="key">
                      <el-input placeholder="请输入" v-model="element.content">
                      </el-input>
                    </el-form-item>
                    <el-form-item class="oper">
                      <el-popconfirm width="fit-content" confirm-button-text="确认" cancel-button-text="取消"
                        title="确认删除这条记录?" @confirm="onDeleteContent(index)">
                        <template #reference>
                          <el-button type="danger" link @click.stop>删除
                          </el-button>
                        </template>
                      </el-popconfirm>
                      <i class="iconfont iconmove sortable-drag"></i>
                    </el-form-item>
                  </div>
                </template>
              </sa-draggable>
              <el-button class="add-params" type="primary" plain icon="Plus" @click="onAddContent">添加
              </el-button>
            </div>
          </el-form-item>
        </template>
      </el-form>
    </el-main>
    <el-footer class="sa-footer--submit">
      <el-button v-if="modal.params.type == 'add' || modal.params.type == 'copy'"
        v-auth="'shop.admin.dispatch.dispatch.add'" type="primary" @click="confirm">保存</el-button>
      <el-button v-if="modal.params.type == 'edit'" v-auth="'shop.admin.dispatch.dispatch.edit'" type="primary"
        @click="confirm">更新</el-button>
    </el-footer>
  </el-container>
</template>
<script setup>
  import { onMounted, reactive, ref, unref } from 'vue';
  import { api } from './dispatch.service';
  import { useModal } from '@/sheep/hooks';
  import SaDraggable from 'vuedraggable';
  import AreaSelect from '../data/area/select.vue';
  import { cloneDeep } from 'lodash';

  const emit = defineEmits(['modalCallBack']);
  const props = defineProps({
    modal: {
      type: Object,
    },
  });

  // 添加 编辑 form
  let formRef = ref(null);
  const form = reactive({
    model: {
      name: '',
      type: props.modal.params.dispatchType,
      express: [],
      autosend: {
        type: "text",
        content: ""
      }
    },
    rules: {
      name: [{ required: true, message: '请输入模板名称', trigger: 'blur' }],
    },
  });
  const loading = ref(false);

  const priceType = ref('number');

  //Draggable
  const templateRules = {
    first_num: [{ required: true, message: '请输入数量', trigger: 'blur' }],
    first_price: [{ required: true, message: '请输入运费', trigger: 'blur' }],
    additional_num: [{ required: true, message: '请输入数量', trigger: 'blur' }],
    additional_price: [{ required: true, message: '请输入续费', trigger: 'blur' }],
    district_text: [{ required: true, message: '请选择可配送区域', trigger: 'blur' }],
  };
  function addTemplate() {
    form.model.express.push({
      type: priceType.value,
      first_num: 0,
      first_price: 0,
      additional_num: 0,
      additional_price: 0,
      province_ids: '',
      city_ids: '',
      district_ids: '',
    });
  }
  function deleteTemplate(index) {
    form.model.express.splice(index, 1);
  }

  //选择区域
  function selectArea(index) {
    useModal(
      AreaSelect,
      {
        title: '区域选择',
        selected: {
          province: form.model.express[index].province_ids,
          city: form.model.express[index].city_ids,
          district: form.model.express[index].district_ids,
        },
      },
      {
        confirm: (res) => {
          let text = [];
          for (var key in res.data) {
            let ids = [];
            for (var id in res.data[key]) {
              ids.push(id);
              text.push(res.data[key][id]);
            }
            form.model.express[index][key + '_ids'] = ids.join(',');
          }
          form.model.express[index].district_text = text.join(',');
        },
      },
    );
  }

  function onChangeAutosendType(type) {
    form.model.autosend.content = type == 'text' ? '' : []
  }
  function onAddContent() {
    if (!form.model.autosend.content) {
      form.model.autosend.content = []
    }
    form.model.autosend.content.push({
      title: '',
      content: '',
    });
  }
  function onDeleteContent(index) {
    form.model.autosend.content.splice(index, 1);
  }

  // 获取详情
  async function getDetail(id) {
    loading.value = true;
    const { error, data } = await api.detail(id, {
      type: props.modal.params.dispatchType,
    });
    if (error === 0) {
      form.model = data;
      if (props.modal.params.dispatchType == 'express') {
        priceType.value = form.model.express.length > 0 ? form.model.express[0].type : 'number';
      }
    }
    loading.value = false;
  }

  // 表单关闭时提交
  async function confirm() {
    // 表单验证
    unref(formRef).validate(async (valid) => {
      if (!valid) return;

      let submitForm = cloneDeep(form.model);

      if (props.modal.params.dispatchType == 'express') {

        submitForm.express.forEach((ex) => {
          ex.type = priceType.value;
        });

        if (props.modal.params.type == 'copy') {
          delete submitForm.id;
          submitForm.express.forEach((express) => {
            delete express.id;
          });
        }
      }else if(props.modal.params.dispatchType == 'autosend'){
        if (props.modal.params.type == 'copy') {
          delete submitForm.id;
        }
      }

      const { error } =
        props.modal.params.type == 'add' || props.modal.params.type == 'copy'
          ? await api.add(submitForm)
          : await api.edit(props.modal.params.id, submitForm);
      if (error == 0) {
        emit('modalCallBack', { event: 'confirm' });
      }
    });
  }

  onMounted(() => {
    if (props.modal.params.id) {
      getDetail(props.modal.params.id);
    }
  });
</script>
<style lang="scss" scoped>
  .template-wrap {
    width: 100%;
    min-width: 490px;
    color: var(--sa-font);
    .title {
      width: inherit;
      background: var(--sa-table-header-bg);
      height: 40px;
      margin: 0 0 12px;
      font-size: 12px;
    }
    .area {
      width: 320px;
      padding-left: 16px;
      font-weight: bold;
    }
    .num {
      width: 140px;
      padding-left: 16px;
      font-weight: bold;
    }
    .item {
      display: flex;
      .area {
        width: 320px;
        padding-left: 16px;
        .area-edit {
          width: 100%;
        }
      }
      .num {
        width: 140px;
        padding-left: 10px;
        :deep() {
          .el-form-item__content {
            height: 32px;
          }
        }
      }
    }
  }
  :deep() {
    .el-form-item__content {
      margin-left: 0 !important;
    }
  }
</style>
